<?php
namespace App\Repos;

use App\Models\ShopRecharge;
use App\Models\ShopEnvelope;
use App\Services\RedisService;
use EasyWeChat;
use function EasyWeChat\Kernel\Support\generate_sign;
use DB;


class ShopRechargeRepo
{
	public static function  getPages($where=[],$num=10)
	{	   
	  	$list = ShopRecharge::where($where)->paginate($num); 
	  	return $list;     
	}

	public static function find($where)
	{
		
		$order = ShopRecharge::where($where)->first();
		return $order;
	}

	/**
	 * 创建红包
	 */
	public static function create($data)
	{		
		DB::beginTransaction();
		try {
			$openid = $data['openid'];
			$data  = array_only($data,['code','shop_id','money','source','shop_user_id']);
			$rs    = ShopRecharge::create($data);
			$unifyData['openid']       = $openid;
			$unifyData['total_amount'] = (int)$data['money'];
			$unifyData['code']         = $data['code'];
			DB::commit();
		} catch (\Exception $e) {
			dd($e->getMessage());			
			DB::rollBack();
			return false;
		}
		return self::wechatUnifyOrder($unifyData);
	}

	
	

	

	public static function wechatUnifyOrder($data)
	{
		$payment = EasyWeChat::payment('shop'); // 微信支付
		$result = $payment->order->unify([
		    'body'         => '幸福壹选红包充值',
		    'out_trade_no' => $data['code'],
		    'trade_type'   => 'JSAPI',  // 必须为JSAPI
		    'openid'       => $data['openid'], // 这里的openid为付款人的openid
		    'total_fee'    => $data['total_amount'], // 总价单位分
		    'notify_url'   => config('app.url').'/wechat/recharge-notify'
		]);

		// 如果成功生成统一下单的订单，那么进行二次签名
		if ($result['return_code'] === 'SUCCESS') {
		    // 二次签名的参数必须与下面相同
		    $params = [
		        'appId'     => config('wechat.mini_program.shop.app_id'),
		        'timeStamp' => time(),
		        'nonceStr'  => $result['nonce_str'],
		        'package'   => 'prepay_id=' . $result['prepay_id'],
		        'signType'  => 'MD5',
		    ];
		    // config('wechat.payment.default.key')为商户的key
		    $params['paySign'] = generate_sign($params, config('wechat.payment.shop.key'));
		    $params['order_code']    = $data['code'];
		    $params['order_created'] = date('Y-m-d H:i:s');
		    return $params;
		} else {
		    return $result;
		}

	}



	public static function createEnvelop($data)
	{
		$envelops = generateEnvolpeArr($data['money']);		
		foreach ($envelops as $key => $e) {
			$v['recharge_id'] = $data['recharge_id'];
			$v['shop_id'] 	  = $data['shop_id'];
			$v['money'] 	  = $e;
			$se = ShopEnvelope::create($v); 
			$key = 'fruit:shops:envelops:'.$data['shop_id'];
			$value = json_encode(['id'=>$se->id,'money'=>$e]);
			RedisService::lpush($key,$value);
		}
		return true;	
	}


	

	

	

	
	
	

	
	
	
}